<template>
  <div style="margin:20px" >
    <el-form label-width="120px">
      <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title"/>
      </el-form-item>
      <el-form-item label="课程讲师">
        <el-select v-model="courseInfo.teacherId">
          <el-option v-for="t in teachers" :key="t.id" :label="t.name" :value="t.id"/>
        </el-select>
      </el-form-item>

      <el-form-item label="课程类别">
        <el-select
          v-model="courseInfo.subjectParentId"
          placeholder="父分类"
          @change="handlePSubjectChange">
          <el-option v-for="ps in levelOneSubjects" :key="ps.id" :label="ps.title" :value="ps.id"/>
        </el-select>
        <el-select v-model="courseInfo.subjectId" placeholder="子分类">
          <el-option v-for="cs in levelTwoSubjects" :key="cs.id" :label="cs.title" :value="cs.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="课程课时">
        <el-input-number v-model="courseInfo.lessonNum" :min="0" controls-position="right" />
      </el-form-item>

      <el-form-item label="课程简介">
        <tinymce v-model="courseInfo.description"/>
      </el-form-item>
      <el-form-item label="课程封面">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :action="uploadPath"
          class="avatar-uploader">
          <img v-if="courseInfo.cover" :src="courseInfo.cover" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>
      <el-form-item label="课程价格">
        <el-input-number v-model="courseInfo.price" :min="0" controls-position="right" />
      </el-form-item>
    </el-form>
    <div style="text-align:center">
      <!-- :disabled="flag":防止表单重复提交 -->
      <el-button :disabled="flag" type="primary" plain @click="saveAndNext">保存并下一步</el-button>
    </div>
  </div>
</template>

<script>
import tinymce from '@/components/Tinymce'
import teacherApi from '@/api/teacher'
import subjectApi from '@/api/subject'
import courseApi from '@/api/course'

export default {
  components: {
    tinymce
  },
  data() {
    return {
      uploadPath: 'http://localhost:8120/admin/oss/file/upload?module=cover', // 把存的地址改到我们模块的cover下
      courseInfo: {
        subjectId: '',
        lessonNum: 0,
        price: 0
      },
      flag: false,
      teachers: [],
      levelOneSubjects: [],
      levelTwoSubjects: []
    }
  },
  created() {
    // 判断  如果路径中包含 课程id的参数  代表当前页面是通过编辑跳转过来的
    if (this.$route.query.id) {
      this.$parent.courseId = this.$route.query.id
    }
    this.teacherList()
    subjectApi.getNestedSubjects().then(r => {
      this.levelOneSubjects = r.data.items
      // 判断如果form.vue中courseId有值  查询课程基本信息回显
      if (this.$parent.courseId) {
        courseApi.getCourseInfo(this.$parent.courseId).then(r => {
          this.courseInfo = r.data.item
          // 已经获取到一级分类的id，再查询他的子分类
          this.levelOneSubjects.forEach(ps => {
            if (ps.id === this.courseInfo.subjectParentId) {
              this.levelTwoSubjects = ps.children
              return
            }
          })
        })
      }
    })
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.courseInfo.cover = res.data.path
      this.$forceUpdate()// 强制渲染
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handlePSubjectChange(id) {
      // 清空显示的二级分类缓存
      this.courseInfo.subjectId = ''
      console.log(id)
      // 需要根据一级分类的id获取一级分类json对象，一级分类对象的children属性代表他的二级分类集合
      this.levelOneSubjects.forEach(ps => {
        if (ps.id === id) {
          this.levelTwoSubjects = ps.children
          return
        }
      })
    },
    teacherList() {
      teacherApi.teacherList().then(r => {
        // console.log(r.data)teacherList
        this.teachers = r.data.items
      })
    },

    saveAndNext() {
      if (this.flag) {
        return
      }
      this.flag = true
      if (this.$parent.courseId) {
        // 更新
        this.update()
      } else {
        // 新增
        this.save()
      }
    },
    update() {
      courseApi.updateCourseInfo(this.courseInfo, this.$parent.courseId).then(r => {
        console.log(r.data.id)
        // 缓存 新增的课程id 因为第二步 第三步需要使用该id，第一步回显课程信息也需要使用
        // this.$parent.courseId = r.data.id
        this.$parent.active = 1
      })
    },
    save() {
      // 跳转到下一个页面：只需要修改父vue页面中的form.vue中的active的值
      /**
      * vue父子组件通信：
      *     1、父组件获取子组件；调用方法
      *         this.$refs.ref值.属性/方法()
      *     2、子组件获取父组件
      *         this.$parent
      */
      courseApi.saveCourseInfo(this.courseInfo).then(r => {
        console.log(r.data.id)
        // 缓存 新增的课程id 因为第二步 第三步需要使用该id，第一步回显课程信息也需要使用
        this.$parent.courseId = r.data.id
        this.$parent.active = 1
      })
    }
  }
}
</script>
<style>
.tinymce-container {
  position: relative;
  line-height: normal;
}

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 356px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 356px;
    height: 178px;
    display: block;
  }
</style>
